package com.jrx.anytxn.transaction.job.paph.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * @author LY
 * @Description 合并分库文件监听，删除指定目录下的同步数据文件和md5文件
 */
@Service
public class MergeBankFileListener implements JobExecutionListener {

	private static final Logger logger = LoggerFactory.getLogger(MergeBankFileListener.class);
	@Autowired
	private IOrganizationTableService organizationTableService;

	@Autowired
	private PaphFileConfig paphFileConfig;

	@Override
	public void beforeJob(JobExecution jobExecution) {

		// 检查放款转账相关文件是否存在，存在则删除
		checkFile(Constant.PRODECUT_TYPE_XF, paphFileConfig.getTraAcctDetailFilePath(),
				TransBizConstant.TRA_ACCT_DETAIL);
		checkFile(Constant.PRODECUT_TYPE_JY, paphFileConfig.getTraAcctDetailFilePath(),
				TransBizConstant.TRA_ACCT_DETAIL);

		// 检查还款计划相关文件是否存在，存在则删除
		checkFile(Constant.PRODECUT_TYPE_JY, paphFileConfig.getPlanFilePath(), TransBizConstant.PLAN_FILE_NAME);
		checkFile(Constant.PRODECUT_TYPE_XF, paphFileConfig.getPlanFilePath(), TransBizConstant.PLAN_FILE_NAME);

		// 检查扣款结果相关文件是否存在，存在则删除
		checkFile(Constant.PRODECUT_TYPE_JY, paphFileConfig.getRepayDetailFilePath(), TransBizConstant.PREPAY_DETAIL);
		checkFile(Constant.PRODECUT_TYPE_XF, paphFileConfig.getRepayDetailFilePath(), TransBizConstant.PREPAY_DETAIL);
	}

	private void checkFile(String productType, String filePath, String fileType) {
		PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
		String nextProcessDate = DateUtils.format(org.getNextProcessingDate(), "yyyyMMdd");
		String dataFileName = Constant.LS_BANK + productType + nextProcessDate + fileType + ".txt";
		String md5FileName = Constant.LS_BANK + productType + nextProcessDate + fileType + ".md5";
		filePath =
				filePath + org.getTenantId() + File.separator + nextProcessDate + File.separator + productType;
		Path fPath =
				Paths.get(filePath);
		Path dPath = Paths.get(fPath + File.separator + dataFileName);
		Path mPath = Paths.get(fPath + File.separator + md5FileName);
		if (!Files.exists(fPath)) {
			try {
				Files.createDirectories(fPath);
			} catch (IOException e) {
				logger.error("目录创建失败", e);
				throw new RuntimeException("目录创建失败", e);
			}
		}

		if (Files.exists(dPath)) {
			try {
				Files.delete(dPath);
			} catch (IOException e) {
				logger.error("文件{}删除失败", dPath);
				throw new RuntimeException("文件删除失败", e);
			}
		}
		if (Files.exists(mPath)) {
			try {
				Files.delete(mPath);
			} catch (IOException e) {
				logger.error("文件{}删除失败", mPath);
				throw new RuntimeException("文件删除失败", e);
			}
		}

		// 创建文件
		try {
			Files.createFile(dPath);
			Files.createFile(mPath);
		} catch (IOException e) {
			logger.error("创建文件失败", e);
		}

	}

	@Override
	public void afterJob(JobExecution jobExecution) {

	}
}
